using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WPCoco.Tasks
{
    public class Repeat : Task, IContainer<Task>
    {
        public Repeat(Task task, int times)
        {
            this.task = task; this.times = times;
        }

        Task task;
        int times;
        int count;

        public override void Initialize()
        {
            base.Initialize();
            count = times + 1;
        }

        public override void Update(float time)
        {
            if (HasEnded()) return;
            if (count == times + 1)
            {
                task.StartTime = time;
                task.Initialize();
                count--;
            }
            while (task.HasEnded()) 
            {
                task.Finish();
                task.StartTime = time;
                task.Initialize();
                count--;
                if (count == 0) return;
            }
            task.Update(time - task.StartTime);
        }

        public override bool HasEnded()
        {
            return count == 0;
        }

        public override void Finish()
        {

        }

        public override Task Clone()
        {
            return new Repeat(task.Clone(), times);
        }

        public override Task Reverse()
        {
            return new Repeat(task.Reverse(), times);
        }

        #region IContainer<Task> Members

        public IEnumerable<Task> GetContainerEnumerator()
        {
            yield return task;
            yield break;
        }

        #endregion
    }
}
